package com.xinlong.shop.framework.sms;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import darabonba.core.client.ClientOverrideConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @Author Sylow
 * @Description
 * @Date: Created in 00:46 2023/1/1
 */
@Component
public class AliyunSMS {
    private final static Logger logger = LoggerFactory.getLogger(AliyunSMS.class);

    private final AliyunSMSConfig aliyunSMSConfig;

    public AliyunSMS(AliyunSMSConfig aliyunSMSConfig) {
        this.aliyunSMSConfig = aliyunSMSConfig;
    }

    /**
     * 发送验证码
     * @param phone 手机号
     * @param code 验证码
     * @return
     */
    public boolean sendCode(String phone, String code) throws ExecutionException, InterruptedException {

        String accessKeyId = aliyunSMSConfig.getAccessKeyId();
        String accessKeySecret = aliyunSMSConfig.getAccessKeySecret();
        String regionId = aliyunSMSConfig.getRegionId();
        String signName = aliyunSMSConfig.getSignName();
        String templateCode = aliyunSMSConfig.getTemplateCode();

        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(accessKeyId)
                .accessKeySecret(accessKeySecret)
                //.securityToken("<your-token>") // use STS token
                .build());

        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region(regionId) // Region ID
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                )
                .build();

        // Parameter settings for API request
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .phoneNumbers(phone)
                .signName(signName)
                .templateCode(templateCode)
                .templateParam("{\"code\":\"" + code + "\"}")
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();

        // Asynchronously get the return value of the API request
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // Synchronously get the return value of the API request
        SendSmsResponse resp = response.get();
        boolean result;
        if (!"OK".equals(resp.getBody().getCode())) {
            result = false;
            logger.warn("短信发送失败，错误：{}", resp.getBody().getMessage());
        } else {
            result = true;
        }
        //resp.getBody().getCode()
        client.close();

        return result;
    }

}
